package cn.xxstudy.blog.config

import org.apache.catalina.Context
import org.apache.catalina.connector.Connector
import org.apache.tomcat.util.descriptor.web.SecurityCollection
import org.apache.tomcat.util.descriptor.web.SecurityConstraint
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory
import org.springframework.boot.web.servlet.server.ServletWebServerFactory
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

/**
 * 作者：wuxinxi on 2020/12/9
 * 包名：cn.xxstudy.blog.config
 * TODO:请求配置【http、https】
 * 请求http时重定向要https
 */
@Configuration
class TomcatConfig {

    @Value("\${server.http.port}")
    private var httpPort: Int = 80

    @Value("\${server.port}")
    private var httpsPort: Int = 443

    @Bean
    fun connector(): Connector {
        val connector = Connector("org.apache.coyote.http11.Http11NioProtocol")
        connector.port = httpPort
        connector.redirectPort = httpsPort
        return connector
    }

    @Bean
    fun servletContainer(connector: Connector): ServletWebServerFactory {
        val tomcat = object : TomcatServletWebServerFactory() {
            override fun postProcessContext(context: Context) {
                super.postProcessContext(context)
                val securityConstraint = SecurityConstraint()
                securityConstraint.userConstraint = "CONFIDENTIAL"
                val connection = SecurityCollection()
                connection.addPattern("/*")
                securityConstraint.addCollection(connection)
                context.addConstraint(securityConstraint)
            }
        }
        tomcat.addAdditionalTomcatConnectors(connector)
        return tomcat
    }
}